<template>
  <div class="current-students">
    <div class="current-students-search">
      <div class="use-btn">
        <div class="collapse-btn" @click="setCollapse">
          <span v-if="!isCollapse"
            >展开<el-icon style="margin-left: 10px"
              ><ArrowDown /></el-icon></span
          ><span v-else
            >收起<el-icon style="margin-left: 10px"><ArrowUp /></el-icon
          ></span>
        </div>
      </div>
      <el-form :model="form" ref="ruleFormRef" label-width="auto">
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="搜索学员:">
              <el-input
                v-model="searchName"
                style="width: 80%"
                placeholder="请输入学员姓名/手机号"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学员来源:">
              <el-select
                v-model="searchJoinWay"
                placeholder="请选择学员来源"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in joinWayList.value"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年级:">
              <el-select
                v-model="gradeName"
                placeholder="请选择年级"
                style="width: 80%"
                @change="toSearch"
                clearable
              >
                <el-option
                  v-for="item in gradeList.value"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="toSearch"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="toClear(ruleFormRef)"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <div class="search-collapse" v-show="isCollapse">
          <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="6">
              <el-form-item label="所在班级:">
                <el-select
                  v-model="classN"
                  placeholder="请选择所在班级"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in classList.value"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="学员创建人:">
                <el-select
                  v-model="creatorName"
                  placeholder="请选择学员创建人"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in followPeopleList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  >
                    {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="padding-right: 4%">
              <el-form-item label="创建时间:">
                <el-date-picker
                  v-model="cTime"
                  type="daterange"
                  unlink-panels
                  range-separator="~"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="6">
              <el-form-item label="跟进人:">
                <el-select
                  v-model="people"
                  placeholder="请选择跟进人"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in followPeopleList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  >
                    {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="学管师:">
                <el-select
                  v-model="studyPeople"
                  placeholder="请选择学管师"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in managerPeopleList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  >
                    {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="班级老师:">
                <el-select
                  v-model="classPeople"
                  placeholder="请选择班级老师"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in teacherList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <!-- <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="6">
              <el-form-item label="学员年龄:">
                <el-time-picker
                  v-model="value1"
                  is-range
                  range-separator="To"
                  start-placeholder="Start time"
                  end-placeholder="End time"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生日:">
                <el-input
                  v-model="searchStudents"
                  placeholder="请输入学员姓名/手机号"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
          </el-row> -->
        </div>
      </el-form>
    </div>
    <div class="manage-students">
      <!-- <el-button type="primary">发消息</el-button> -->
      <el-button
        plain
        @click="openShareDialog('跟进人')"
        v-hasPermi="['sales:clue:distribute']"
        >分配跟进人</el-button
      >
      <el-button
        plain
        @click="openShareDialog('学管师')"
        v-hasPermi="['student:manager:add']"
        >分配学管师</el-button
      >
      <!-- <el-button type="plain" plain icon="Upload" @click="handleImport"
        >导入学员</el-button
      >
      <el-button type="plain" plain icon="Download" @click="handleExport"
        >导出学员</el-button
      > -->
      <!-- <el-dropdown placement="bottom-start" style="margin-left: 13px">
        <el-button> 更多操作 </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>群发短信</el-dropdown-item>
            <el-dropdown-item>批量删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->
    </div>
    <!-- 表格 -->
    <div class="students-table">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="学员姓名" width="180" fixed="left">
          <template #default="scope">
            <router-link
              :to="'/registrar/studentsDetails/detail/' + scope.row.id"
              class="link-type"
            >
              <div style="display: flex; align-items: center">
                <span
                  style="margin-right: 10px; color: #67c23a; cursor: pointer"
                  >{{ scope.row.name }}</span
                >
                <el-icon v-if="scope.row.gender == '1'" style="color: #fb6465"
                  ><Female
                /></el-icon>
                <el-icon
                  v-else-if="scope.row.gender == '0'"
                  style="color: #4791ed"
                  ><Male
                /></el-icon>
              </div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          property="mobile"
          label="手机号"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="joinName"
          label="学员来源"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          label="年龄"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        >
          <template #default="scope">
            {{ scope.row.ageName ? `${scope.row.ageName}岁` : "-" }}
          </template>
        </el-table-column>
        <el-table-column
          property="birthday"
          label="出生日期"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="className"
          label="所在班级"
          show-overflow-tooltip
          :formatter="formatName"
          width="140"
        />
        <el-table-column
          property="gradeName"
          label="年级"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="attendSchool"
          label="学校"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <!-- <el-table-column
          property="remark"
          label="标签"
          show-overflow-tooltip
          :formatter="formatName"
        /> -->
        <el-table-column
          property="counselor"
          label="跟进人"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="management"
          label="学管师"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="creatName"
          label="学员创建人"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
          fixed="right"
        />
        <el-table-column
          property="addTime"
          label="创建时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
          fixed="right"
        />
        <!-- <el-table-column label="操作" width="130" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="toGetCurrentStudentsList"
      />
      <div style="height: 10px"></div>
    </div>
    <ShareDialog
      :isShowShare="isShowShare"
      :shareType="shareType"
      :students="multipleSelection"
      @update:isShowShare="updateShowShare"
      @update:tableList="toGetCurrentStudentsList"
    />
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?stage=2'"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Pagination from "@/components/Pagination/index.vue";
import ShareDialog from "../shareDialog/index.vue";
import { ref, reactive, provide } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import useRegistrarStore from "@/store/modules/registrar";
import {
  getStudentsList,
  getJoinWayList,
  getTeacherList,
  getManagerList,
  getFollowPeopleList,
  getClassList,
  getGradeList,
  deleteClue,
  toExport,
  toExportTemplate,
} from "@/api/studentManagement/index.js";
import {
  getToken,
  getLoginDeptParentAuth,
  getLoginDeptAuth,
} from "@/utils/auth";
const { proxy } = getCurrentInstance();
const loading = ref(true);
//创建store
const registrarStore = useRegistrarStore();
//筛选
const searchName = ref(""); //学员搜索
const cTime = ref("");
//获取学员来源下拉列表
const searchJoinWay = ref(""); //学员来源
const joinWayList = reactive([]); //学员来源列表
provide("joinWayList", joinWayList); //传值给后代
const toGetJoinWayList = async () => {
  try {
    const res = await getJoinWayList();
    if (res.code == 200) {
      joinWayList.value = res.data;
      registrarStore.setJoinWayList(joinWayList.value);
    }
  } catch (error) {
    console.error("获取学员来源下拉列表失败:", error);
  }
};
onMounted(toGetJoinWayList);
//跟进人&学员创建人
const people = ref(""); //跟进人
const creatorName = ref(""); //学员创建人
const followPeopleList = ref([]);
const toFollowPeopleList = async () => {
  try {
    const res = await getFollowPeopleList({ pageNum: 1, pageSize: 9999 });
    if (res.code == 200) {
      followPeopleList.value = res.rows;
    }
  } catch (error) {
    console.error("获取学员创建人下拉列表失败:", error);
  }
};
onMounted(toFollowPeopleList);
//学管师
const managerPeopleList = ref([]);
const studyPeople = ref(""); //学管师
const toGetManagerList = async () => {
  try {
    const res = await getManagerList({ pageNum: 1, pageSize: 9999 });
    if (res.code == 200) {
      managerPeopleList.value = res.data;
    }
  } catch (error) {
    console.error("获取学管师下拉列表失败:", error);
  }
};
onMounted(toGetManagerList);
//班级老师
const teacherList = ref([]);
const classPeople = ref(""); //班级老师
const toGetTeacherList = async () => {
  try {
    const res = await getTeacherList({});
    if (res.code == 200) {
      teacherList.value = res.data;
    }
  } catch (error) {
    console.error("获取班级老师下拉列表失败:", error);
  }
};
onMounted(toGetTeacherList);
//获取所在班级下拉列表
const classN = ref("");
const classList = reactive([]); //所在班级列表
const toGetClassList = async () => {
  try {
    const res = await getClassList({});
    if (res.code == 200) {
      classList.value = res.data;
      registrarStore.setClassList(classList.value);
    }
  } catch (error) {
    console.error("获取所在班级下拉列表失败:", error);
  }
};
onMounted(toGetClassList);
//获取年级下拉列表
const gradeName = ref("");
const gradeList = reactive([]); //所在班级列表
const toGetGradeList = async () => {
  try {
    const res = await getGradeList({});
    if (res.code == 200) {
      gradeList.value = res.data;
      registrarStore.setGradeList(gradeList.value);
    }
  } catch (error) {
    console.error("获取年级下拉列表失败:", error);
  }
};
onMounted(toGetGradeList);

//筛选学员列表
function toSearch() {
  console.log("ctime", cTime.value);

  toGetCurrentStudentsList();
}

//控制折叠
const isCollapse = ref(true);
function setCollapse() {
  isCollapse.value = !isCollapse.value;
}
//控制分配弹窗
const isShowShare = ref(false);
const shareType = ref(1);
const openShareDialog = (type) => {
  if (multipleSelection.value.length) {
    shareType.value = type;
    isShowShare.value = true;
  } else {
    ElMessage({
      message: "请选择要分配的学员",
      type: "warning",
    });
  }
};
const updateShowShare = (value) => {
  isShowShare.value = value;
};

//表格多选操作
const multipleTableRef = ref();
const multipleSelection = ref([]);
const toggleSelection = () => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      // multipleTableRef.value!.toggleRowSelection(row, undefined)
    });
  } else {
    // multipleTableRef.value!.clearSelection()
  }
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("444", multipleSelection.value);
};
//分页器
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
//处理日期格式
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
//获取表格数据
const tableData = ref([]);
const toGetCurrentStudentsList = async () => {
  loading.value = true;
  const params = {
    stage: 2,
    type: 4,
    mine: 0,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    wxParam: searchName.value,
    joinWay: searchJoinWay.value,
    counselorId: people.value,
    managementId: studyPeople.value,
    classId: classN.value,
    gradeId: gradeName.value,
    creator: creatorName.value,
    startTime: cTime.value ? formatDate(cTime.value[0]) : "",
    endTime: cTime.value ? formatDate(cTime.value[1]) : "",
  };
  // console.log('params', params.startTime)

  try {
    const res = await getStudentsList(params);
    if (res.code == 200) {
      total.value = res.total;
      tableData.value = res.rows;
      loading.value = false;
    }
  } catch (error) {
    console.error("获取学生列表失败:", error);
  }
};
onMounted(toGetCurrentStudentsList);
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === "" || cellValue === null ? "-" : cellValue;
};

//删除学员
const handleDelete = (row) => {
  ElMessageBox.confirm("是否删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteClue({
          id: row.id,
          type: 1,
        });
        if (res.code == 200) {
          toGetCurrentStudentsList();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
        }
      } catch (error) {
        console.error("删除失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
//清空搜索内容
const toClear = () => {
  searchName.value = "";
  searchJoinWay.value = "";
  people.value = "";
  studyPeople.value = "";
  classN.value = "";
  gradeName.value = "";
  cTime.value = "";
  toGetCurrentStudentsList();
};

//导入导出部分---------------------------------------------------------
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "导入学员",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 0,
  // 设置上传的请求头部
  headers: {
    Authorization: "Bearer " + getToken(),
    LoginDeptParentAuth: getLoginDeptParentAuth(),
    LoginDeptAuth: getLoginDeptAuth(),
  },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/student/import",
});
//导入
function handleImport() {
  upload.open = true;
  //importClassListAPI().then((res) => {});
}
//确定导入
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
//取消导入
const cancelImport = () => {
  upload.open = false;
  proxy.$refs["uploadRef"].clearFiles();
};
const handleFileSuccess = (res) => {
  upload.open = false;
  proxy.$refs["uploadRef"].clearFiles();
  pageNum.value = 1;
  toGetCurrentStudentsList();
  if (res.code == 200) {
    ElMessage({
      message: res.msg,
      type: "success",
    });
  } else {
    ElMessage({
      message: res.msg,
      type: "error",
    });
  }
};
const handleFileError = (err) => {
  console.log("上传失败:", err);
  ElMessage({
    message: "上传失败",
    type: "error",
  });
};

//导出
function handleExport() {
  toExport({ stage: 2, type: 4, mine: 0 }).then((res) => {
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8",
    });
    //var contentDisposition = decodeURI(res.headers["content-disposition"]);
    const url = window.URL.createObjectURL(blob),
      link = document.createElement("a"); // 创建a标签
    link.href = url;
    link.download = "在读学员列表";
    link.click();
    URL.revokeObjectURL(url); // 释放内存
    proxy.$modal.msgSuccess("导出成功");
  });
}

/** 下载模板操作 */
function importTemplate() {
  toExportTemplate({ stage: 2 })
    .then((res) => {
      let blob = new Blob([res], {
        type: "application/vnd.ms-excel;charset=utf-8",
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "导入模板.xls";
      document.body.appendChild(a); // 添加到 DOM
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    })
    .catch((error) => {
      console.error("下载模板失败:", error);
    });
}
</script>

<style lang="scss" scoped>
.current-students {
  height: 100%;
  overflow: auto;
  // position: relative;
  .current-students-search {
    position: relative;
    .use-btn {
      position: absolute;
      top: 0;
      right: 0;
      // display: flex;
      // align-items: center;
      // justify-content: space-between;
      // width: 10%;
      height: 30px;
      z-index: 100;
      cursor: pointer;
      .collapse-btn {
      }
    }
    .search-label {
      display: inline-block;
      width: 18%;
      text-align: right;
      margin-right: 8px;
      font-size: 14px;
    }
    .current-students-search-main {
      // width: 90%;
    }
  }
  .manage-students {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    height: 40px;
    // background-color: red;
  }
}
</style>
